const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/*封装的提示方法*/
function showErr(err) {
  wx.showToast({
    title: err,
    icon: 'loading',
    duration: 2000
  })
}

/*封装的request方法*/
function wxRequest(that, pathRoot, pathLast, data, sucFunc) {
  wx.request({
    url: pathRoot + pathLast,
    method: 'post',
    data: data,
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      sucFunc(that, res);
    },
    fail: function (e) {
      wx.showToast({
        title: '网络异常！',
        icon: 'loading',
        duration: 2000
      });
    },
  });
}

/*封装的设置缓存的方法*/
function setStorage(key, value) {
  wx.setStorage({
    key: key,
    data: value,
    success: function () {
      console.log('缓存设置成功')
    }
  })
}

/*封装的提取缓存的方法*/
function getStorage(that, key, storageSucFunc, storageFailFunc) {
  wx.getStorage({
    key: key,
    success: function (res) {
      storageSucFunc(that, res)
    },
    fail: function () {
      storageFailFunc(that)
    }
  })
}

/*获取缓存的所有的key*/
function getAllStorageKey(that) {
  wx.getStorageInfo({
    success: function (res) {
      that.setData({
        storageKey: res.keys
      })
      console.log(that.data.storageKey)
    }
  })
}

/*封装方法打电话*/
function giveCall(tel) {
  wx.makePhoneCall({
    phoneNumber: tel
  })
}

function removeStorageKey(key) {
  wx.removeStorage({
    key: key,
    success: function (res) {
      console.log('缓存清除成功')
    }
  })
}

function openLocation(lo, la, name, address) {
  wx.openLocation({
    latitude: parseFloat(la),
    longitude: parseFloat(lo),
    scale: 28,
    name: name,
    address: address
  })
}

module.exports = {
  formatTime: formatTime,
  showErr: showErr,
  wxRequest: wxRequest,
  setStorage: setStorage,
  getStorage: getStorage,
  getAllStorageKey: getAllStorageKey,
  removeStorageKey: removeStorageKey,
  giveCall: giveCall,
  openLocation: openLocation
}
